package com.example.okhttputils.mvp.model.api;

import android.text.TextUtils;
import android.util.Log;

import com.example.okhttputils.mvp.base.App;
import com.example.okhttputils.mvp.base.Constant;
import com.example.okhttputils.mvp.ui.util.AppUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * @author:created by njb
 * 时间:2019/3/8 15 01
 * 描述:
 */
public class ApiRetrofit {
    private static ApiRetrofit apiRetrofit;
    private Retrofit retrofit;
    private OkHttpClient client;
    private ApiServer apiServer;
    private String rand;
    private String TAG = "ApiRetrofit";


    /**
     * 请求访问quest
     * response拦截器
     */
    private Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long startTime = System.currentTimeMillis();
            Response response = chain.proceed(chain.request());

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            okhttp3.MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            Log.e(TAG, "----------Request Start----------------");
            Log.e(TAG, "| " + request.toString() + request.headers().toString());
            Log.e(TAG, "| Response:" + AppUtils.unicodeToUTF_8(content));
            Log.e(TAG, "----------Request End:" + duration + "毫秒----------");
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
        }
    };
    //
    private Interceptor headInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            rand = df.format(System.currentTimeMillis());

            Request request = chain.request().newBuilder()
                    .addHeader("clienttype", "1")
                    .addHeader("sdk_type", "android")
                    .addHeader("sdk_version_name",AppUtils.getAppVersionName(App.getContext()))
                    .addHeader("sdk_version", AppUtils.getAppVersionCode(App.getContext()) + "")
                   // .addHeader("Cookie", UserImpl.getCookie())
                    .build();


            return chain.proceed(request);
        }
    };

    public ApiRetrofit() {


        client = new OkHttpClient.Builder()
                //添加log拦截器
                .addInterceptor(interceptor)
                .addInterceptor(headInterceptor)
//                .cookieJar(new CookiesManager(fdfjds.getContext()))
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();


        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                //支持RxJava2
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();

        apiServer = retrofit.create(ApiServer.class);
    }

    public static ApiRetrofit getInstance() {
        if (apiRetrofit == null) {
            synchronized (Object.class) {
                if (apiRetrofit == null) {
                    apiRetrofit = new ApiRetrofit();
                }
            }
        }
        return apiRetrofit;
    }

    public ApiServer getApiService() {
        return apiServer;
    }

    public static String getUserAgent(){
        return "ChuangYeTianXia/"+AppUtils.getAppVersionName(App.getContext())+"(Android : "+ "1.4.0)";
    }
}
